package com.pap.gateway.config;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.pap.base.util.string.StringUtilss;
import com.pap.gateway.dynamicrouter.router.DynamicRouteServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

/**
 *  路由初始化， 从 nacos 中获取 配置的路由信息，进行路由 加载。
 */
@Component
public class InitGateWayRouterConfig {

    private static Logger logger  =  LoggerFactory.getLogger(InitGateWayRouterConfig.class);

    @Value(value = "${spring.cloud.nacos.config.server-addr}")
    private String papNacosServerAdd;

    @Value(value = "${spring.cloud.nacos.config.namespace}")
    private String papNacosNameSpace;

    @Autowired
    private DynamicRouteServiceImpl dynamicRouteService;

    @PostConstruct
    public void init() {
        try {
            Properties gatewayProperties = new Properties();
            gatewayProperties.put(PropertyKeyConst.SERVER_ADDR, papNacosServerAdd);
            gatewayProperties.put(PropertyKeyConst.NAMESPACE, papNacosNameSpace);
            ConfigService configService = NacosFactory.createConfigService(gatewayProperties);
            String routerStr = configService.getConfig("com.pap.gateway.config.router", "GATEWAY_GROUP", 5000);
            List<RouteDefinition> definitionList = new ArrayList<RouteDefinition>();
            if(StringUtilss.isNotEmpty(routerStr)) {
                ObjectMapper mapper = new ObjectMapper();
                definitionList = mapper.readValue(routerStr, new TypeReference<List<RouteDefinition>>() {});
            }
            dynamicRouteService.update(definitionList);
        } catch (IOException e) {
            logger.error("InitGateWayRouterConfig.init.路由初始化更新: [{}]", e.getMessage());
        }catch (NacosException e) {
            logger.error("InitGateWayRouterConfig.init.路由初始化更新: [{}]", e.getMessage());
        }
    }
}

